import os
import shutil
import sys

from diff_print import OperationPrint
from diff_make_same import OperationMakeSame

Operation = None

def WalkPath(path):
  try:
    ls = os.listdir(path)
  except:
    print('Access deny!')
    sys.exit()
  else:
    dirs = []
    files = []
    for l in ls:
      subpath = os.path.join(path, l)
      if (os.path.isdir(subpath)):
        dirs.append(l)
      else:
        files.append(l)
    dirs.sort()
    files.sort()
    return dirs, files

def DiffList(src_path, dst_path, src_list, dst_list, is_path):
  global Operation
  i = 0
  j = 0
  while (i < src_list.__len__() and j < dst_list.__len__()):
    if (src_list[i] < dst_list[j]):
      Operation(src_path, dst_path, src_list[i], 1)
      i += 1
    elif (src_list[i] > dst_list[j]):
      Operation(src_path, dst_path, dst_list[j], 0)
      j += 1
    else:
      if (is_path):
        src_subpath = os.path.join(src_path, src_list[i])
        dst_subpath = os.path.join(dst_path, dst_list[j])
        DiffPath(src_subpath, dst_subpath)
      i += 1
      j += 1

  while (i < src_list.__len__()):
    Operation(src_path, dst_path, src_list[i], 1)
    i += 1
  while (j < dst_list.__len__()):
    Operation(src_path, dst_path, dst_list[j], 0)
    j += 1

def DiffPath(src_path, dst_path):
  global Operation
  src_dirs, src_files = WalkPath(src_path)
  dst_dirs, dst_files = WalkPath(dst_path)
  # print((src_path + ': src_dirs: ' + str(src_dirs)).encode('gbk'))
  # print((dst_path + ': dst_dirs: ' + str(dst_dirs)).encode('gbk'))
  # print((src_path + ': src_files: ' + str(src_files)).encode('gbk'))
  # print((dst_path + ': dst_files: ' + str(dst_files)).encode('gbk'))

  DiffList(src_path, dst_path, src_dirs, dst_dirs, 1)
  DiffList(src_path, dst_path, src_files, dst_files, 0)

if __name__ == '__main__':
  if (sys.argv.__len__() != 4):
    print('Invalid parameters!')
    sys.exit()

  if (sys.argv[3] == 'print'):
    Operation = OperationPrint
  elif (sys.argv[3] == 'same'):
    Operation = OperationMakeSame
  else:
    print('Invalid diff operation!')
    sys.exit(1)
    
  DiffPath(sys.argv[1], sys.argv[2])
